package org.yzh.web.service.impl;

import com.github.dozermapper.core.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yzh.web.component.mybatis.Page;
import org.yzh.web.component.mybatis.PageInfo;
import org.yzh.web.component.mybatis.Pagination;
import org.yzh.web.mapper.AlarmCountMapper;
import org.yzh.web.model.entity.AlarmCountDO;
import org.yzh.web.model.vo.*;
import org.yzh.web.service.AlarmCountService;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author lsj
 * @date 2021/1/16 18:57
 */
@Service
public class AlarmCountServiceImpl implements AlarmCountService {

    @Autowired
    private AlarmCountMapper alarmCountMapper;

    @Autowired
    private Mapper dozerMapper;

    @Override
    public List<AlarmCountDO> find(AlarmCountQuery query) {
        return alarmCountMapper.find(query);
    }

    @Override
    public CountAndSummary<AlarmCount> findAlarmCount(AlarmCountQuery query, PageInfo pageInfo) {
        CountAndSummary<AlarmCount> summary = new CountAndSummary<>();
        dozerMapper.map((Pagination<AlarmCount>)Page.start(() -> alarmCountMapper.findAlarmGroupCount(query), pageInfo), summary);
        AlarmGroup alarmStatistical = alarmCountMapper.findAlarmStatistical(query);
        if (alarmStatistical != null) {
            summary.setAvg(alarmStatistical.getAvg());
            summary.setMax(alarmStatistical.getMax());
        }
        return summary;
    }

    @Override
    public Optional<AlarmCountDO> findUnique(String deviceId, String plateNo, LocalDate date) {
        return this.find(AlarmCountQuery.builder().deviceId(deviceId).plateNo(plateNo).date(date).build()).stream()
            .findFirst();
    }

    @Override
    public List<MileageAlarm> findMileageAlarm(DateTimeQuery query) {
        return alarmCountMapper.findMileageAlarm(query);
    }

    @Override
    public int batchInsert(List<AlarmCountDO> records) {
        return alarmCountMapper.batchInsert(records);
    }

    @Override
    public int insert(AlarmCountDO record) {
        return alarmCountMapper.batchInsert(Collections.singletonList(record));
    }

    @Override
    public int update(AlarmCountDO record) {
        return alarmCountMapper.update(record);
    }

    @Override
    public int upsert(AlarmCountDO record) {
        Optional<AlarmCountDO> unique = findUnique(record.getDeviceId(), record.getPlateNo(), record.getDate());
        if (unique.isPresent()) {
            record.setId(unique.get().getId());
            return this.update(record);
        }
        return this.insert(record);
    }

}
